import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { ReturnModelType } from '@typegoose/typegoose';
import { User } from 'libs/db/src/model/user.model';
import { InjectModel } from 'nestjs-typegoose';
import { WorkspaceService } from 'src/workspace/workspace.service';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel(User) private readonly userModel: ReturnModelType<typeof User>,
    private readonly workspaceService: WorkspaceService,
  ) {}

  async create(newUser: User): Promise<User> {
    const password = newUser.password;
    const saltOrRounds = 10;
    newUser.password = await bcrypt.hash(password, saltOrRounds);

    // 要创建一个user
    let user = await this.userModel.create(newUser);
    // 然后在user下
    this.workspaceService.create(
      {
        name: '默认workspace',
      },
      user._id,
    );
    return user;
  }

  async findOne(username: string): Promise<User | undefined> {
    return this.userModel.findOne({ username });
  }
}
